
//Copyright 1997-2009 Syrinx Development, Inc.
//This file is part of the Syrinx Web Application Framework (SWAF).
// == BEGIN LICENSE ==
//
// Licensed under the terms of any of the following licenses at your
// choice:
//
//  - GNU General Public License Version 3 or later (the "GPL")
//    http://www.gnu.org/licenses/gpl.html
//
//  - GNU Lesser General Public License Version 3 or later (the "LGPL")
//    http://www.gnu.org/licenses/lgpl.html
//
//  - Mozilla Public License Version 1.1 or later (the "MPL")
//    http://www.mozilla.org/MPL/MPL-1.1.html
//
// == END LICENSE ==
using System;
using System.Collections.Generic;
using System.Text;

using Swaf;
using Swaf.BizObj;
using Swaf.BizRule;
using Swaf.Container;
using Swaf.Logging;
using Swaf.Gui.AspNet2;



namespace Localization
{
	public class BaseLocalizationBizRules : Syrinx.BaseBizRules
	{
		private static bool s_setupState = false;
		private static bool s_shouldShowCultureSelection = true;
		private static bool s_shouldPrefixCultureName = false;
		/// <summary>
		/// 
		/// </summary>
		/// <param name="app"></param>
		/// <param name="context"></param>
		/// <param name="noOp"></param>
		/// <returns></returns>
		public IBizObjList loadStartupLocalText(IApplication app, IRuleContext context, string noOp)
		{
			try
			{
				//TODO: swith to DAR call when DB is ready
				//IBizObjList list = (IBizObjList)app.appData.get("Data.Localization.GetAllLocalizationText", new FlexiMap());
				//return list;
				return App.bizObjMgr.createList("LocalString");
			}
			catch (LocalizationException) { throw; }
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="app"></param>
		/// <param name="context"></param>
		/// <returns></returns>
		public IBizObjList getCultureList(IApplication app, IRuleContext context, string appId)
		{
			try
			{
				FlexiMap m = new FlexiMap();
				if (appId == null || appId == "")
					appId = app.resMgr.getMacro("ApplicationId");
				m.put("defaultBrowserLangCode", appId);
				return (IBizObjList)app.appData.get("Data.Localization.GetAppLanguageAvail", m);
			}
			catch (LocalizationException)
			{
				throw;
			}
		}

		/// <summary>
		/// set applicatino culture information
		/// </summary>
		/// <param name="app"></param>
		/// <param name="context"></param>
		/// <param name="culture"></param>
		public void setCurrentCulture(IApplication app, IRuleContext context, string culture)
		{
			//TODO: Setup culture properly
			//app.resMgr.CurrentCulture;
		}

		public IBizObjList getApplicationPages(IApplication app, IRuleContext context, object dummy)
		{
			try
			{
				//TODO: switch to DAR call when DB is ready
				//IBizObjList pages=app.appData.get("Data.Localization.GetAllApplicationPage",new FlexiMap()) as IBizObjList;
				IBizObjList pages = App.bizObjMgr.createList("PageInfo");
				app.appData["ApplicationPages"] = pages;
				return pages;
			}
			catch (LocalizationException) { throw; }
		}

		/// <summary>
		/// pushes a page name and widget to db for localization support
		/// </summary>
		/// <param name="app"></param>
		/// <param name="context"></param>
		/// <param name="pageControlLocalizations"></param>
		public void addApplicationPage(IApplication app, IRuleContext context, Dictionary<string, List<ServerControlLocalizer.LocalizeAttemptInfo>> pageControlLocalizations)
		{
			List<Exception> exceptions = new List<Exception>();
			foreach (KeyValuePair<string, List<ServerControlLocalizer.LocalizeAttemptInfo>> pageInfo in pageControlLocalizations)
			{
				try
				{
					string[] pageNameParts = pageInfo.Key.Split('.');
					string pageName = pageNameParts[pageNameParts.Length - 1];
					string fileName = string.Format("{0}.aspx", pageName);
					FlexiMap m = new FlexiMap();

					// Todo: Must Find a way to remove this. Temporarily this is commented out..
					//IBizObj page = Common.Gui.AspNet.BasePage.ApplicationPages.search("pageName", pageName) as IBizObj;

					//if (page == null)
					   m["APP_SHORT_NAME"] = App.resMgr.getMacro("ApplicationId");
					//else
						//m["APP_SHORT_NAME"] = page.get("appName");

					m["APPLICATION_PAGE_ID"] = 0;
					m["APPLICATION_PAGE_NAME"] = pageName;
					m["APPLICATION_PAGE_PATH"] = fileName;
					m["APPLICATION_PAGE_SENSITIVE_IND"] = "Y";
					m["APP_PAGE_ENTRY_POINT_IND"] = "N";
					m["APP_PAGE_PRINTER_FRIENDLY_IND"] = "N";
					m["CREATED_DTTM"] = DateTime.Now;

					app.appData.put("Data.Localization.InsertApplicationPage", m); //insert application_page record

					foreach (ServerControlLocalizer.LocalizeAttemptInfo info in pageInfo.Value)
					{
						try
						{
							if (!info.LocalizeSuccessful)
							{
								string value = (info.DefaultValue == null) ? "" : info.DefaultValue;
								if (s_shouldPrefixCultureName)
									value = string.Format("{0}{1}", info.CultureName, value);

								//insert ui_element record
								m["UI_ELEMENT_ID"] = 0;
								m["UI_ELEMENT_TYPE_CODE"] = "L";
								m["UI_ELEMENT_NAME"] = info.ControlId;
								m["UI_ELEMENT_DESCRIPTION"] = value;
								app.appData.put("Data.Localization.InsertUIElement", m);

								//insert page_ui_element record on success
								object uiElementId = m["UI_ELEMENT_ID"];
								if (uiElementId is int || uiElementId is short)
									app.appData.put("Data.Localization.InsertPageUIElement", m);

								//insert ui_element_property
								if (uiElementId is int || uiElementId is short)
								{
									m["UI_ELEMENT_PROPERTY_NAME"] = info.ControlPropertyName;
									m["UI_ELEMENT_PROPERTY_DESCRIPTION"] = value;
									app.appData.put("Data.Localization.InsertUIElementProperty", m);
								}

							}
						}
						catch (Exception e) { exceptions.Add(e); }
					}
				}
				catch (Exception e) { exceptions.Add(e); }
			}
			//TODO: check for exceptions in the exceptions list
		}

		public bool shouldShowCultureSelection(IApplication app, IRuleContext context)
		{
			if (!s_setupState)
			{
				bool.TryParse(app.resMgr.getMacro("ShouldShowCultureSelection"), out s_shouldShowCultureSelection);
				bool.TryParse(app.resMgr.getMacro("PrefixControlTextWithCultureNameOnTrackingInsert"), out s_shouldPrefixCultureName);
				s_setupState = true;
			}

			return s_shouldShowCultureSelection;
		}
	}
}
